package xhwl.hmo.mall.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import de.greenrobot.event.EventBus;
import xhwl.android.pay.bean.PayBean;
import xhwl.android.pay.bean.WXPayBean;
import xhwl.android.pay.invoke.PayManager;
import xhwl.android.pay.invoke.PaymentResult;
import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.Constant;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.event.PaymentFinishEvent;
import xhwl.hmo.mall.http.api.OnlinePayApi;
import xhwl.hmo.mall.http.api.WXPrepayidApi;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.WxPrepayidResp;
import xhwl.hmo.mall.utils.AlarmUtil;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.views.MyDialog;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by admin on 2017-10-31.
 */

public class PaymentActivity extends BaseActivity implements View.OnClickListener {
    public static final String EXTRA_ORDER_NO="orderNo";
    public static final String EXTRA_ORDER_NAME="orderName";
    public static final String EXTRA_PRICE="price";
//    public static final String EXTRA_GOOD_TYPE="goodType";
    public static final String EXTRA_ORDER_STATUS="orderStatus";
    private LinearLayout llZFB;
    private LinearLayout llWX;
    MyDialog myDialog;
    String orderNo,orderName,price;
//    String goodType;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        orderNo=getIntent().getStringExtra(EXTRA_ORDER_NO);
        orderName=getIntent().getStringExtra(EXTRA_ORDER_NAME);
        price=getIntent().getStringExtra(EXTRA_PRICE);
//        goodType=getIntent().getStringExtra(EXTRA_GOOD_TYPE);

        SpUtil.putString(SpUtil.ORDER_NO,orderNo);//保存，支付结果通知时使用
        setContentView(R.layout.activity_payment);

    }

    @Override
    public void initViews() {
        initTitleViews();
        this.llWX = (LinearLayout) findViewById(R.id.llWX);
        this.llZFB = (LinearLayout) findViewById(R.id.llZFB);
    }

    @Override
    public void onBackPressed() {
        showDialog();
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("选择付款方式");
    }

    @Override
    public void initListener() {
        this.llWX.setOnClickListener(this);
        this.llZFB.setOnClickListener(this);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.llWX:
                if(!Constant.WEIXIN_PAY_ENABLE){
                    ToastUtil.showToast(mContext,"暂未开通微信支付");
                    return;
                }
                if(vilid()){
                    HttpManager.getInstance().dealHttp(this, new WXPrepayidApi(orderNo, AppUtil.getIp(mContext)), new OnNextListener<WxPrepayidResp>() {
                        @Override
                        public void onNext(WxPrepayidResp resp) {
                            if (resp == null
                                    || StringUtil.isEmpty(resp.prepay_id)) {
                                ToastUtil.showToast(mContext, "生成预付订单失败！");
                                return;
                            }

                            WXPayBean payBean=new WXPayBean(orderNo,orderName,price,resp.prepay_id,resp.nonce_str);
                            PayManager.getInstance().startPayment(PaymentActivity.this,payBean);
                        }
                    });
                }
                break;
            case R.id.llZFB:
                if(vilid()){
                    PayBean payBean=new PayBean(orderNo,orderName,price);
                    PayManager.getInstance().startPayment(PaymentActivity.this,payBean);
                }

                break;

        }
    }
    private boolean vilid() {
        String msg = "";
        if (StringUtil.isEmpty(orderNo)) {
            msg = "订单号不能为空！";
        } else if (StringUtil.isEmpty(orderName)) {
            msg = "订单名称不能为空！";
        }  else if (StringUtil.isEmpty(price)) {
            msg = "订单金额不能为空！";
        } else {
            try {
                double m = Double.parseDouble(price);
                if (m <= 0) {
                    msg = "订单金额不能小于0！";
                }
            } catch (Exception e) {
                // TODO: handle exception
                msg = "订单金额格式错误！";
            }
        }
        if (msg.length() > 0) {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void showDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_exit_pay, null);
        TextView tvExit = (TextView) view.findViewById(R.id.tvExit);
        TextView tvContinue = (TextView) view.findViewById(R.id.tvContinue);
        tvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
                finish();
            }
        });
        tvContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
            }
        });
        myDialog = new MyDialog(this, view, Gravity.CENTER);
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.show();

    }
    public void onEvent(final PaymentResult result){
        if(result==null)
            return;
        String status = "0";// 1-成功 0-失败
        if(result.isSuccess()){
            status = "1";
            String serialNum = result.getMsg();
            OnlinePayApi api=new OnlinePayApi(result.getOrderId(),serialNum,status);
            HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp>() {
                @Override
                public void onNext(HttpResp resp) {
                    if (resp.isOk()||"00042".equals(resp.error_code)) {
                        //取消闹钟
                        AlarmUtil.cancelAlarm(mContext, IntentConstants.Action.orderRemind, Integer.parseInt(result.getOrderId()));
//                        ToastUtil.showToast(mContext,"支付成功");
                        Intent intent=new Intent(mContext,PaymentSuccActivity.class);
                        intent.putExtra(EXTRA_ORDER_NO,result.getOrderId());
                        startActivity(intent);
                        finish();
                    }
                    else{
                        ToastUtil.showToast(mContext,resp.message);
                        Intent intent=new Intent(mContext,PaymentFailActivity.class);
                        intent.putExtra(EXTRA_ORDER_NO,result.getOrderId());
                        startActivity(intent);
                    }
                }
            });
        }


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myDialog!=null&&myDialog.isShowing()){
            myDialog.dismiss();
        }
        EventBus.getDefault().post(new PaymentFinishEvent());
        EventBus.getDefault().unregister(this);
    }
}
